<template>
  <slide-right>
    <div class="calendar">
      <div class="calender-header">
        <div class="date-bar">
          <ul>
            <li v-for="item in weeks"
                :key="item.id">{{item.name}}</li>
          </ul>
        </div>
      </div>
      <div class="calendar-con-box">
        <div class="scrollCalendar"
             ref="scrollCalendar">
          <div class="calendar-content">
            <div class="one-month"
                 v-for="(item,index) in aYearData"
                 :key="index">
              <div :id="`monthTit${item.aMouseData[8].yy.toString()+item.aMouseData[8].mm.toString()}`"
                   class="month-title"
                   :ref="`${item.title}`">{{item.title}}</div>
              <div class="month-data-box">
                <div class="a-day"
                     :class="{'on'
                :mItem.type !== 'pre' && idx == aDayClsIdx && aMouthClsIdx == index&&everTag}"
                     v-for="(mItem,idx) in item.aMouseData"
                     :key="idx"
                     @click="clkdayBoxFn(mItem,idx,index,item.title,mItem.content)"
                     :ref="`${mItem.yy}-${mItem.mm>9?mItem.mm:'0'+mItem.mm}-${mItem.content>9?mItem.content:'0'+mItem.content}`">
                  <span>{{mItem.festival}}</span>
                  <p>{{mItem.content}}</p>
                  <b :class="mItem.minimum?'minimum':''">{{mItem.price?'￥'+mItem.price:''}}</b>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </slide-right>
</template>

<script>
import BScroll from 'better-scroll';
import SlideRight from '@/components/slideRight';
import { mapState, mapMutations } from 'vuex';
import GetLunarDayData from './lunar.js';

export default {
  data () {
    return {
      // 过去日期标签
      everTag: false,
      activeCls: ' on',
      everCls: ' gray',
      // 一天的类名
      aDayClsIdx: 0,
      aMouthClsIdx: 0,
      weeks: [
        { id: 0, name: '日', fullName: '周日' },
        { id: 1, name: '一', fullName: '周一' },
        { id: 2, name: '二', fullName: '周二' },
        { id: 3, name: '三', fullName: '周三' },
        { id: 4, name: '四', fullName: '周四' },
        { id: 5, name: '五', fullName: '周五' },
        { id: 6, name: '六', fullName: '周六' },
      ],
      month: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
      // 排序后的月份
      orderMonth: [],
      aYearData: [],
      // 当前年月日
      nowYY: '',
      nowMM: '',
      nowDD: '',
      // 选中的日期
      selDate: '',
      // 缓存到本地的城市数据
      // cityCache: '',
      // 缓存日期
      cacheDate: '',
      // 日历价格数据
      priceData: [
        {
          date: '2019-01-04',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-01-05',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-01-06',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-01-07',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-01-08',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-01-09',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-01-10',
          price: 80,
          minimum: true,
        },
        {
          date: '2019-02-04',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-02-05',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-02-06',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-02-13',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-02-14',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-02-15',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-02-16',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-02-17',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-02-18',
          price: 60,
          minimum: true,
        },
        {
          date: '2019-02-19',
          price: 120,
          minimum: false,
        },
        {
          date: '2019-02-20',
          price: 180,
          minimum: false,
        },
        {
          date: '2019-02-25',
          price: 180,
          minimum: false,
        },
        {
          date: '2019-02-26',
          price: 220,
          minimum: false,
        },
        {
          date: '2019-02-27',
          price: 180,
          minimum: false,
        },
      ],
      // 公历节日
      GregorianFtv: {
        '01-01': '元旦',
        '02-14': '情人节',
        // '03-08': '妇女节',
        // '03-12': '植树节',
        // '03-15': '消费者权益日',
        // '04-01': '愚人节',
        '05-01': '劳动节',
        // '05-04': '青年节',
        // '05-12': '护士节',
        '06-01': '儿童节',
        // '07-01': '建党节',
        // '08-01': '建军节',
        '09-10': '教师节',
        // '09-28': '孔子诞辰',
        '10-01': '国庆节',
        // '10-06': '老人节',
        // '10-24': '联合国日',
        '12-24': '平安夜',
        '12-25': '圣诞节',
      },
      // 农历节日
      LunarFtv: {
        正月初一: '春节',
        正月十五: '元宵节',
        // 四月初五: '清明节',
        五月初五: '端午节',
        // 七月初七: '七夕',
        // '07-15': '中元节',
        八月十五: '中秋节',
        // '09-09': '重阳节',
        // '12-08': '腊八节',
        // '12-24': '小年',
      },
      // 农历类
      instace: '',
    };
  },
  computed: {
    ...mapState(['dateCache']),
  },
  components: {
    SlideRight,
  },
  created () {
    // 实例化农历类
    if (!this.instace) {
      this.instace = new GetLunarDayData();
    }

    // 获取当前年月日
    this.nowYY = new Date().getFullYear();
    this.nowMM = new Date().getMonth();
    this.nowDD = new Date().getDate();
    this.get_aYear_Data();

    // 获取缓存的日期
    this.cacheDate = this.dateCache.takeoffDate;
  },
  mounted () {
    this.$nextTick(() => {
      // 日历滚动到指定位置
      this.scrollCalendar = new BScroll(this.$refs.scrollCalendar, {
        click: true,
      });
      const selMonth = this.cacheDate.toString().substr(0, 4).toString() + (this.cacheDate.toString().substr(5, 2) * 1).toString();
      this.scrollCalendar.scrollToElement(`#monthTit${selMonth}`);
    });

    // 为已过期的日期添加样式
    for (let i = 1; i < this.nowDD; i++) {
      this
        .$refs[`${this.nowYY}-${this.nowMM + 1 > 9 ? this.nowMM + 1 : `0${this.nowMM + 1}`}-${i > 9 ? i : `0${i}`}`][0]
        .className += this.everCls;
    }
    // 为已选日期添加样式
    this.$refs[this.cacheDate][0].className += this.activeCls;
  },
  methods: {
    ...mapMutations(['setDateCache']),
    /**
     * 返回上一页
     */
    backPrePage () {
      this.$router.go(-1);
    },
    // 获取某一天是星期几
    getWeekByDay (dayValue) { // dayValue=“2014-01-01”
      const day = new Date(Date.parse(dayValue.replace(/-/g, '/'))); // 将日期值格式化
      const today = []; // 创建星期数组
      this.weeks.map((item) => {
        today.push(item.fullName);
        return true;
      });
      return today[day.getDay()]; // 返一个星期中的某一天，其中0为星期日
    },
    // 一年月份排序
    orderMonthFunc () {
      this.month.map((item) => {
        if (item >= this.nowMM) {
          this.orderMonth.push(item);
        }
        return true;
      });
      this.month.map((item) => {
        if (item < this.nowMM) {
          this.orderMonth.push(item);
        }
        return false;
      });
    },
    // 获取一年的日历数据
    get_aYear_Data () {
      // 当前时间加一年的月份
      const aYear = [];
      this.orderMonthFunc();
      this.orderMonth.map((item) => {
        if (item >= this.nowMM) {
          aYear.push({ year: this.nowYY, month: item });
        } else {
          aYear.push({ year: this.nowYY + 1, month: item });
        }
        return false;
      });

      aYear.map((item) => {
        this.aYearData.push({
          title: `${item.year}年${item.month + 1}月`,
          aMouseData: this.get_amonth_list(item.year, item.month),
        });
        return true;
      });
    },
    // 获取一个月的列表
    get_amonth_list ($yy, $mm) {
      // 定义每个月的天数，如果是闰年第二月改为29天
      // year=2018;month=1(js--month=0~11)
      const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
      if (($yy % 4 === 0 && $yy % 100 !== 0) || $yy % 400 === 0) {
        daysInMonth[1] = 29;
      }

      // 获得指定年月的1号是星期几
      const targetDay = new Date($yy, $mm, 1).getDay();
      // 将要在calendar__main中渲染的列表
      const calendarList = [];
      const preNum = targetDay;
      // 首先先说一下，我们的日期是(日--六)这个顺序也就是(0--6)
      // 有了上述的前提我们可以认为targetDay为多少，我们就只需要在calendarList的数组中push几个content为''的obj作为占位
      if (targetDay > 0) {
        for (let i = 0; i < preNum; i++) {
          const obj = {
            type: 'pre',
            content: '',
          };
          calendarList.push(obj);
        }
      }

      for (let i = 0; i < daysInMonth[$mm]; i++) {
        const obj = {
          type: 'normal',
          content: i + 1,
          yy: $yy,
          mm: $mm + 1,
        };
        // 添加日历价格
        this.priceData.map((pItem, p) => {
          const priceYY = pItem.date.substr(0, 4);
          const priceMM = pItem.date.substr(5, 2);
          const priceDD = pItem.date.substr(8, 2);
          if ($yy === priceYY * 1 && ($mm + 1) === priceMM * 1 && (i + 1) === priceDD * 1) {
            obj.price = pItem.price;
            obj.minimum = pItem.minimum;
          }
        });
        // 添加公历节日
        const mmdd = `${$mm + 1 < 10 ? `0${$mm + 1}` : ($mm + 1)}-${i + 1 < 10 ? `0${i + 1}` : (i + 1)}`;
        if (this.GregorianFtv[mmdd]) {
          obj.festival = this.GregorianFtv[mmdd];
        }
        // 添加农历节日
        const lunarYY = $yy;
        const lunarMM = $mm + 1 > 10 ? ($mm + 1) : `0${$mm + 1}`;
        const lunarDD = (i + 1) > 10 ? (i + 1) : `0${i + 1}`;
        const lunarDate = this.instace.GetLunarDay(lunarYY, lunarMM, lunarDD).substr(-4, 4);
        if (this.LunarFtv[lunarDate]) {
          obj.festival = this.LunarFtv[lunarDate];
        }

        // 添加节气
        const JieQiName = this.instace.getJieQi(lunarYY, lunarMM, lunarDD);
        if (JieQiName !== '') {
          obj.festival = JieQiName;
        }
        calendarList.push(obj);
      }

      return calendarList;
    },
    // 点击一天，改变样式，获取选中值
    /**
     * @param {object} data 一天的数据
     * @param {number} idx 选中的天序号
     * @param {number} index 选中的年序号
     * @param {string} selYYMM 选中的年月值
     * @param {number} selDD 选中的天值
     */
    clkdayBoxFn (data, idx, index, selYYMM, selDD) {
      if (data.type !== 'pre') {
        this.aMouthClsIdx = index;
        this.aDayClsIdx = idx;
        const selYY = selYYMM.substring(0, selYYMM.indexOf('年'));
        const selMM = selYYMM.substring(selYYMM.indexOf('年') + 1, selYYMM.indexOf('月'));

        this.selDate = `${selYY}-${selMM > 9 ? selMM : `0${selMM}`}-${selDD > 9 ? selDD : `0${selDD}`}`;

        this.everTag = false;
        // 过去的日期不可选
        if (Date.parse(this.selDate) - Date.parse(`${this.nowYY}-${this.nowMM + 1}-${this.nowDD}`) >= 0) {
          this.everTag = true;
          // 缓存选中的日期数据
          const takeoffDate = this.selDate;
          let week = '';

          // 今天不显示星期显示为“今天”
          const nowDateInfo = `${this.nowYY}-${this.nowMM + 1 > 10 ? (this.nowMM + 1) : `0${this.nowMM + 1}`}-${this.nowDD > 10 ? this.nowDD : `0${this.nowDD}`}`;
          if (takeoffDate === nowDateInfo) {
            week = '今天';
          } else {
            week = this.getWeekByDay(takeoffDate);
          }
          this.setDateCache({ takeoffDate, week });
          this.$refs[this.cacheDate][0].className = 'a-day';

          setTimeout(() => {
            this.backPrePage();
          }, 100);
        }
      }
      return true;
    },
  },
};
</script>

<style lang="less" scoped>
@import '../../style/mobilecommon.less';
@import 'calendar.less';
</style>
